<template>
  <div class="addNews">
    <tmpHeader :index='10'/>
    <h2 style="text-align:center;font-weight:600;margin-bottom:10px;color: #333">院内动态新闻发布编辑</h2>
    <div class="main">
      <p class="title">基本信息</p>
      <Row gutter="24" class="box">
          <Col span="16">
            <!--新闻标题-->
            <div class="main_title">
              <div class="main_title_info">
                <span style="color:red;">*&nbsp;&nbsp;</span>
                <span>新闻标题:</span>
              </div>
              <div class="input">
                <Input v-model.trim="title" placeholder="请输入新闻标题" style="width:90%;" :maxlength="30" />
                <span>{{ title.length }}/30</span>
              </div>
            </div>
          </Col>
          <Col span="8">
            <!--新闻来源-->
            <div class="main_source">
              <div class="main_title_info">
                <span style="color:red;">&nbsp;&nbsp;</span>
                <span>内容来源:</span>
              </div>
              <Input v-model.trim="isource" placeholder="请输入新闻的来源" :maxlength="50" style="width: 100%"/>
            </div>
          </Col>
          <Col span="8">
            <!--添加大图-->
            <div class="main_imgs">
              <div class="main_title_info">
                <span style="color:red;">&nbsp;&nbsp;</span>
                <span>列表首图:</span>
              </div>
              <div class="demo-upload-list" v-for="(item,index) in uploadList" :key='index'>
                <div v-if="item.status === 'finished'">
                  <img :src="item.url">
                  <div class="demo-upload-list-cover">
                    <Icon type="ios-eye-outline" @click.native="handleView(item.name)"></Icon>
                    <Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
                  </div>
                </div>

                <div v-else>
                  <Progress v-if="item.showProgress" :percent="item.percentage" hide-info></Progress>
                </div>
              </div>
              <Upload
                v-show="uploadList.length ==0"
                ref="upload"
                :show-upload-list="false"
                :default-file-list="defaultList"
                :on-success="handleSuccess"
                :format="['jpg','jpeg','png']"
                :max-size="2000"
                :on-format-error="handleFormatError"
                :on-exceeded-size="handleMaxSize"
                :before-upload="handleBeforeUpload"
                multiple
                type="drag"
                :action="uploadUrl"
                :headers="fromData"
                :data="uploadData"
                style="display: inline-block;width:58px;"
              >
                <div style="width: 58px;height:58px;line-height: 58px;">
                  <i class = "iconfont icon-shangchuan" style="font-size:20px;"></i>
                </div>
              </Upload>
              <small style="color:#FF9966;margin-top:5px;margin-left:10px">（备注：图片大小不超过1024kb，建议方图170*170px,长图100*85px）</small>
              <Modal title="预览图片" v-model="visible" footer-hide>
                <img :src=" uploadList[0].url " v-if="visible" style="width: 100%">
              </Modal>
            </div>
          </Col>
          <Col span="8">
            <div class="main_source" style="margin-top:40px;">
              <div class="main_title_info">
                <span style="color:red;">&nbsp;&nbsp;</span>
                <span>发布终端:</span>
              </div>
              <Select class="w-select" v-model="info.type">
                  <Option
                      :value="item.id"
                      v-for="item in tabList"
                      :key="item.id"
                      style='text-align:center;'
                  >{{item.name}}</Option>
              </Select>
            </div>
          </Col>
          <Col span="8">
            <!--是否显示-->
            <div class="main_ishow" style="margin-top:40px;">
              <div class="main_title_info">
                <span style="color:red;">&nbsp;&nbsp;</span>
                <span>是否发布:</span>
              </div>
              <iSwitch size="large"  v-model="enable">
                  <span slot="open">开启</span>
                  <span slot="close">关闭</span>
              </iSwitch>
            </div>
          </Col>
          <Col span="23">
          <!--排序-->
            <div class="main_sort">
              <div class="main_title_info">
                <span style="color:red;">&nbsp;&nbsp;&nbsp;</span>
                <span>列表排序:</span>
              </div>
              <InputNumber :max="99999" :min="1" v-model.trim="isort" style="width: 100px" placeholder="无"></InputNumber>
              <small style="color:#FF9966;margin-top:5px;margin-left:10px">&nbsp;&nbsp;&nbsp;备注:只能填写数字,1代表置顶以此类推</small>
            </div>
          </Col>
        </Row>
    </div> 
    <div class="main">  
      <p class="title">详细内容</p>
        <!--新闻内容-->
        <div class="main_content box">
          <div class="main_title_info">
            <span style="color:red;">*&nbsp;&nbsp;</span>
            <span>新闻内容:</span>
          </div>
          <div class="shuru">
            <vueEditor
              id="editor_id"
              :textHtml="info.content"
              :urlCode="urlCode"
              @valueHandle="afterChange"
              style="width:100%"
            ></vueEditor>
          </div>
        </div>
    </div>
    <!--保存-->
    <div class="save">
      <Button type="primary" @click="save" :disabled='disabledSave' style="width:75px;height:35px;">
        <Icon type="ios-checkmark" style="margin-right: 5px" />保存
      </Button>
        <Button @click="back" style="width:75px;height:35px;">
          <i class = "iconfont icon-butongyi" style="font-size:14px;margin-right:5px"></i>取消
        </Button>
    </div>
  </div>
</template>

<script>
import api from "@/api/commonApi";
import tmpHeader from "@/pages/organizat/contentmen/tmpHeader";
import vueEditor from "@/components/vueEditor";
import code from "@/configs/base.js";
export default {
  components: {
    tmpHeader,
    vueEditor
  },
  data() {
    return {
      title: "",
      isort: 1,
      isource: "",
      enable: true,
      info: {
        content: "",
        type: 1
      },
      tabList: [
        // { id: 0, name: "全部" },
        { id: 1, name: "院内通知" },
        { id: 2, name: "医生端" },
        { id: 3, name: "门诊出诊" },
        { id: 4, name: "就诊须知" },
        { id: 5, name: "医保指南" },
        { id: 6, name: "价格公示" },
        { id: 7, name: "热点信息" },
        { id: 8, name: "党风廉政" },
        { id: 9, name: "职权考核" },
        { id: 10, name: "科室职责" },
      ],
      defaultList: [],
      imgName: "",
      visible: false,
      uploadList: [],
      
      uploadModal: true,
      activeUploadId: "5c2bf345-b973-4ffd-a52e-87bb9c1d2b72",
      uploadUrl: api.fileAll,
      uploadData: {
        json: '{"urlCode":"' + code.urlCode.hospitalDynamicNews + '"}'
      },
      images: "",
      id: sessionStorage.getItem("hospitalId"),
      source: "",
      urlCode: '{"urlCode":"' + code.urlCode.richText + '"}',
      disabledSave: false
    };
  },
  created(){
    let breadList = [
            { path: "/index", title: "首页" },
            {
                path: "/index/operation/mechanism/index",
                title: "机构运营"
            },
            {
                path: "/index/operation/home",
                title: "机构配置管理"
            }
        ];
        this.$emit("changeBreadList", breadList);
  },
  mounted() {
    this.uploadList = this.$refs.upload.fileList;
    let _id = this.$route.params.id;
    if (_id) {
      this.$axios
        .post(api.findnewsById, {
          hospitalId: this.id,
          id: _id
        })
        .then(res => {
          if (res.data.success) {
            let ret = res.data.object;
            this.title = ret.title;
            this.info.content = ret.content;
            this.info.type = Number(ret.type)
            this.isource = ret.source;
            this.isort = ret.showindex;
            this.enable = Boolean(ret.enable);
            if (ret.img) {
              this.uploadList.push({
                name: "a42bdcc1178e62b4694c830f028db5c0",
                percentage: 100,
                status: "finished",
                uid: 1544263544970,
                url: this.analysisImages(ret.img)
              });
              this.source = ret.img;
              this.images = ret.img;
            }
          } else {
            this.$Message.error("查询动态新闻失败!")
          }
        })
        .catch(err => {
          console.log(err);
        });
    }
  },
  methods: {
    afterChange(val) {
      this.info.content = val;
    },
    handleView(name) {
      this.imgName = name;
      this.visible = true;
    },
    handleRemove(file) {
      const fileList = this.$refs.upload.fileList;
      this.$refs.upload.fileList.splice(fileList.indexOf(file), 1);
    },
    handleSuccess(res, file) {
      res = this.uploadFileDecrypt(res);
      file.url = this.fileBaseUrl + res.object[0].fileName;
      this.images = JSON.stringify(res.object[0]);
      file.name = res.object[0].fileName;
    },
    handleFormatError(file) {
      this.$Notice.warning({
        title: "格式错误",
        desc: "文件 " + file.name + " 上传失败,请重试"
      });
    },
    handleMaxSize(file) {
      this.$Notice.warning({
        title: "文件过大",
        desc: `文件${file.name}过大，文件最大限制为1024KB`
      });
    },
    handleBeforeUpload() {
      const check = this.uploadList.length < 1;
      if (!check) {
        this.$Message.info("只能上传一张图片");
      }
      return check;
    },
    save() {
      this.disabledSave = true
      let params = {};
      let images = "";
      if (this.images != "" && this.uploadList.length) {
        images = this.images;
      } else if (this.uploadList.length) {
        images = this.source;
      } else {
        images = "";
      }
      params = {
        content: this.info.content,
        type: this.info.type.toString(),
        enable: Number(this.enable),
        hospitalId: this.id,
        showindex: this.isort,
        source: this.isource,
        title: this.title.trim(),
        id: this.$route.params.id
      };
      params.img = images;
      if (this.title == "") {
        this.$Message.info("新闻标题不能为空");
        this.disabledSave = false
      } else if (this.info.content == "") {
        this.$Message.info("新闻内容不能为空");
        this.disabledSave = false
      } 
      // else if (params.newsHeadlines == "") {
      //   this.$Message.info("新闻首图不能为空");
      //   this.disabledSave = false
      // } 
      else {
        this.$axios
          .post(api.updateNews, params)
          .then(res => {
            if (res.data.success) {
              this.$Message.info("修改成功");
              let pageNo = this.$route.params.pageNo;
                setTimeout(() => {
                  this.disabledSave = false
                  this.functionJS.paramsNavgationTo(this, "newsHome", {
                    // 公用方法
                    pageNo
                  }); 
                }, 500);
            } else {
              this.$Message.info("修改动态新闻失败!");
              this.disabledSave = false
            }
          })
          .catch(err => {
            this.disabledSave = false
            console.log(err);
          });
      }
    },
    back() {
      let pageNo = this.$route.params.pageNo;
      this.functionJS.paramsNavgationTo(this, "newsHome", {
        // 公用方法
        pageNo
      }); 
    },
    analysisImages(json) {
      try {
        json = JSON.parse(json);
        return this.fileBaseUrl + json.fileName;
      } catch (error) {
        return "";
      }
    }
  }
};
</script>
<style scoped lang="less">
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  overflow: hidden;
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.w-select{
  width: 100px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.addNews {
    width: calc(100%);
    padding: 10px 30px;
    margin: 0 auto;
    background: #fff;
  .main {
    width: 98%;
    display: flex;
    flex-direction: column;
    margin: 10px auto;
    border: 1px solid #f0f0f0;
    box-shadow: 0 4px 3px #ebedf8;
    border-radius: 5px;
    margin-bottom: 20px;
    .box{
      padding: 0 40px 20px 40px;
    }
    .title {
      font-size: 20px;
      padding-left: 15px;
      margin-bottom: 20px;
      color: #333;
      height: 40px;
      line-height: 40px;
      background: #ebedf8;         
    }
    .main_title {
      width: 100%;
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      height: 30px;
      line-height: 30px;
      .main_title_info {
        min-width: 120px;
      }
      .input {
        position: relative;
        width: 100%;
        span {
          position: absolute;
          right: 10px;
          top: 50%;
          transform: translateY(-50%);
        }
      }
    }
    .main_imgs {
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      height: 100px;
      align-items: center;
      width: 100%;
      .main_title_info {
        min-width: 100px;
      }
      p {
        margin-left: 15px;
      }
    }
    .main_content {
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      width: 100%;
      .main_title_info {
        min-width: 100px;
      }
      .shuru {
        width: 100%;
        div {
          margin: 0;
        }
      }
    }
    .main_source {
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      width: 100%;
      .main_title_info {
        min-width: 100px;
      }
      input {
        width: 400px;
        outline: none;
      }
    }
    .main_sort {
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      width: 100%;
      .main_title_info {
        min-width: 100px;
      }
      input {
        width: 100px;
        outline: none;
      }
      p {
        margin: 0 15px;
      }
    }
    .main_ishow {
      display: flex;
      flex-direction: row;
      margin: 10px auto;
      width: 100%;
      .main_title_info {
        min-width: 100px;
      }
    } 
  }
  .save {
      width: 100%;
      height: 30px;
      text-align: center;
      margin-bottom: 20px;
    }
}
</style>